package ru.evga.inse.server.gwt.user.client;

import ru.evga.gwt.lib.common.client.place.PlaceImpl;
import ru.evga.inse.server.gwt.common.client.AbstractApp;
import ru.evga.inse.server.gwt.user.client.menu.MenuItem;
import ru.evga.inse.server.gwt.user.client.menu.MenuPlaceUtil;
import ru.evga.inse.server.gwt.user.client.place.UserClientPlaceHistoryMapper;

import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.core.client.GWT;
import com.google.gwt.place.shared.PlaceHistoryHandler;


/**
 * User application
 */
public class UserApp
    extends AbstractApp
{
    private IUserAppFactory factory;
    
    private static UserApp INSTANCE;

    static public UserApp getApplicationInstance()
    {
        if(INSTANCE == null)
        {
            IUserAppFactory factory = GWT.create(UserAppFactoryImpl.class); 
            INSTANCE = new UserApp(factory);
        }
        
        return INSTANCE;
    }
    
    private UserApp(IUserAppFactory factory)
    {
        super(factory);
        this.factory = factory;
    }

    protected void init()
    {
        final ActivityManager menuActivityManager = new ActivityManager(factory.getMainMenuActivityMapper(), factory.getEventBus());
        menuActivityManager.setDisplay(factory.getShell().getMainMenu());
        
        final ActivityManager subMenuActivityManager = new ActivityManager(factory.getSubMenuActivityMapper(), factory.getEventBus());
        subMenuActivityManager.setDisplay(factory.getShell().getSubMenu());

        final ActivityManager contentActivityManager = new ActivityManager(factory.getContentActivityMapper(), factory.getEventBus());
        contentActivityManager.setDisplay(factory.getShell().getContent());

        
        UserClientPlaceHistoryMapper mapper = GWT.create(UserClientPlaceHistoryMapper.class);
        PlaceHistoryHandler placeHistoryHandler = new PlaceHistoryHandler(mapper);
        PlaceImpl defaultPlace = MenuPlaceUtil.getBuilderForMenu(MenuItem.GENERAL).build();
        placeHistoryHandler.register(factory.getPlaceController(), factory.getEventBus(), defaultPlace);
        placeHistoryHandler.handleCurrentHistory();
    }
}
